<?php

namespace App\Http\Middleware;

use App\Models\AccessApiLog;
use Closure;
use http\Env\Request;
use Illuminate\Support\Facades\Log;

class MergeHeader
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $reqUrl = $request->fullUrl();
        Log::info("请求【" . $reqUrl . "】 原始Header：" . print_r($this->headerFormat($request->headers->all()), true));
        Log::info("请求方式：". $request->method().":请求【" . $reqUrl . "】 提交内容：" .print_r($request->all(), true));
        $ip = $request->getClientIP();//操作IP
        $identifier = $request->header('Device')?:'';//操作设备码
        $platform = $request->header('Terrace')?:$this->browser();//操作平台/浏览器
        $system_version = $request->header('SystemEdition')?:'';//操作系统版本
        $app_version = $request->header('Application')?:'';//操作App版本
        $auth_token = $request->header('AccessToken');//token
        $hardware = $request->header('hardware');//token
        $request->Merge([
           'ip'=>$ip,
           'identifier'=>$identifier,
           'platform'=>$platform,
           'system_version'=>$system_version,
           'app_version'=>$app_version,
           'auth_token'=>$auth_token,
           'hardware'=>$hardware,
        ]);

//        $this->logs($request);//日志写入
        Log::info("请求【" . $reqUrl . "】 处理后Header：" . print_r($this->headerFormat($request->headers->all()), true));//
        return $next($request);
    }

    private function browser()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'],'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'],'iPad')){
            return 'ios';
        }elseif(strpos($_SERVER['HTTP_USER_AGENT'],'Android')){
            return 'android';
        }else{
            return 'pc';
        }
    }

    /**
     * 格式化Header
     *
     * @param $headers
     * @return array
     */
    public function headerFormat($headers) {
        $headers =array_map(function($item) {
            return $item[0];
        }, $headers);
        return $headers;
    }

}
